import os
import time
import csv
# from datetime import
import uuid
import numpy as np
import pandas as pd
import chardet


class Gantry:
    def __init__(self, file_path):
        self.file_path = file_path
        self.up_gantry = None
        self.down_gantry = None
        self.up_gantry_df = None
        self.down_gantry_df = None

        self.max_speed = 120
        self.dist = None

    def get_gantry_ID(self):
        file_name = os.path.basename(self.file_path)
        # 使用逗号分隔字符串
        parts = file_name.split('-')
        # if parts[0][-5] == '1':
        #     self.up_gantry = parts[0]
        #     self.down_gantry = parts[1]
        # else:
        #     self.up_gantry = parts[1]
        #     self.down_gantry = parts[0]

        self.up_gantry = parts[0]
        self.down_gantry = parts[1]
        # print(self.up_gantry, self.down_gantry)

    def get_data(self):
        # 使用pandas读取CSV文件
        # df = pd.read_csv(self.file_path, sep='\t')
        df = pd.read_excel(self.file_path, engine='openpyxl')
        # 清理列名，去除多余的空格和逗号
        df.columns = [col.strip().replace(',', '') for col in df.columns]
        # # 清理每行数据中的多余符号
        # for col in df.columns:
        #     df[col] = df[col].str.strip(', ')
        # # 筛选 gantryid 列值为 up_gantry 的所有行
        self.up_gantry_df = df[df['门架编号'] == self.up_gantry]
        self.down_gantry_df = df[df['门架编号'] == self.down_gantry]
        # print(self.up_gantry_df)
        # time.sleep(100)

        # # 获取清理后的列名
        # cleaned_column_names = list(df.columns)
        # # 打印列名
        # print("Cleaned Column Names:", cleaned_column_names)

    def get_flow(self, df, time_interval):
        # 将transtime列转换为datetime类型
        df['通行时间'] = pd.to_datetime(df['通行时间'], format='%Y-%m-%d %H:%M:%S')
        # 假设我们按每10分钟统计一次流量
        # 使用pd.Grouper(freq='10T')来定义10分钟的时间窗口, 然后使用size()计算每个时间窗口内的车辆数量, 并重置索引
        # traffic_flow = df.groupby([pd.Grouper(key='transtime', freq='10T')]).size().reset_index(name='vehicle_count')
        grouped = df.groupby([pd.Grouper(key='通行时间', freq=time_interval), '车型']).size().unstack(fill_value=0)
        # 计算总车流量
        total_flow = grouped.sum(axis=1)
        # print(total_flow)
        # 计算各车型占比
        vehicle_percentage = grouped.div(total_flow, axis=0)
        # print(vehicle_percentage)

        return total_flow, vehicle_percentage

    def matching_json(self, up_gantry_df, down_gantry_df, up_path, down_path, up_flag=True, down_flag=True):
        # print(up_gantry_df.columns)
        up_gantry_df['通行时间'] = pd.to_datetime(up_gantry_df['通行时间'], format='%Y-%m-%d %H:%M:%S')
        up_gantry_df['timestamp'] = up_gantry_df['通行时间'].apply(lambda x: x.timestamp())
        up_gantry_df_dict = up_gantry_df.to_dict(orient='records')
        down_gantry_df['通行时间'] = pd.to_datetime(down_gantry_df['通行时间'], format='%Y-%m-%d %H:%M:%S')
        down_gantry_df['timestamp'] = down_gantry_df['通行时间'].apply(lambda x: x.timestamp())
        down_gantry_df_dict = down_gantry_df.to_dict(orient='records')

        # 对上游vlp去重
        up_gantry_df_dict_all = {}
        repeat_list_up = []
        for up_gantry_one in up_gantry_df_dict:
            if up_gantry_one['车牌'] not in up_gantry_df_dict_all.keys():
                up_gantry_df_dict_all[up_gantry_one['车牌']] = [up_gantry_one]
            else:
                # print("多趟次上游", up_gantry_one['vlp'])
                if up_gantry_one['车牌'] not in repeat_list_up:
                    repeat_list_up.append(up_gantry_one['车牌'])
                up_gantry_df_dict_all[up_gantry_one['车牌']].append(up_gantry_one)
        # print("重复上游", repeat_list_up)

        # 对下游vlp去重
        down_gantry_df_dict_all = {}
        repeat_list_down = []
        for down_gantry_one in down_gantry_df_dict:
            if down_gantry_one['车牌'] not in down_gantry_df_dict_all.keys():
                down_gantry_df_dict_all[down_gantry_one['车牌']] = [down_gantry_one]
            else:
                # print("多趟次下游", down_gantry_one['vlp'])
                if down_gantry_one['车牌'] not in repeat_list_down:
                    repeat_list_down.append(down_gantry_one['车牌'])
                down_gantry_df_dict_all[down_gantry_one['车牌']].append(down_gantry_one)
        # print("重复下游", repeat_list_down)

        for repeat_id in repeat_list_up:
            if repeat_id in down_gantry_df_dict_all.keys():
                # 上游匹配下游
                up_gantry_df_dict_list = up_gantry_df_dict_all[repeat_id]   # 多个
                down_gantry_df_dict_list = down_gantry_df_dict_all[repeat_id]   # 一个或多个
                for up_one in up_gantry_df_dict_list:
                    up_one_time = up_one['timestamp']
                    min_diff = 100000
                    target_one = None
                    for down_one in down_gantry_df_dict_list:
                        down_one_time = down_one['timestamp']
                        if up_one_time < down_one_time:
                            diff = down_one_time - up_one_time
                            if diff < min_diff:
                                min_diff = diff
                                target_one = down_one

                    uuid_one = str(uuid.uuid4())
                    if target_one is not None:
                        up_gantry_df_dict_all[repeat_id + uuid_one] = [up_one]
                        down_gantry_df_dict_all[repeat_id + uuid_one] = [target_one]
                        # print("匹配成功", up_one['vlp'], target_one['vlp'])
                        down_gantry_df_dict_all[repeat_id] = [x for x in down_gantry_df_dict_all[repeat_id] if x != target_one]
                    else:
                        # print("匹配失败", up_one['vlp'])
                        up_gantry_df_dict_all[repeat_id + uuid_one] = [up_one]

                # print("删除重复车辆", repeat_id)
                del up_gantry_df_dict_all[repeat_id]
                if len(down_gantry_df_dict_all[repeat_id]) == 0:
                    del down_gantry_df_dict_all[repeat_id]
            else:
                # print("上游多趟次车辆未在下游出现", repeat_id)
                pass

        for repeat_id in repeat_list_down:
            if repeat_id in down_gantry_df_dict_all.keys():
                if repeat_id in up_gantry_df_dict_all.keys():
                    down_gantry_df_dict_list = down_gantry_df_dict_all[repeat_id]   # 多个
                    up_gantry_df_dict_list = up_gantry_df_dict_all[repeat_id]   # 一个
                    for up_one in up_gantry_df_dict_list:
                        up_one_time = up_one['timestamp']
                        min_diff = 100000
                        target_one = None
                        for down_one in down_gantry_df_dict_list:
                            down_one_time = down_one['timestamp']
                            if up_one_time < down_one_time:
                                diff = down_one_time - up_one_time
                                if diff < min_diff:
                                    min_diff = diff
                                    target_one = down_one

                        if target_one is not None:
                            uuid_one = str(uuid.uuid4())
                            up_gantry_df_dict_all[repeat_id + uuid_one] = [up_one]
                            down_gantry_df_dict_all[repeat_id + uuid_one] = [target_one]
                            for i in range(len(down_gantry_df_dict_all[repeat_id])):
                                if down_gantry_df_dict_all[repeat_id][i] != target_one:
                                    uuid_two = str(uuid.uuid4())
                                    down_gantry_df_dict_all[repeat_id + uuid_two] = [down_gantry_df_dict_all[repeat_id][i]]
                        else:
                            # print("下游匹配失败ID", repeat_id)
                            for i in range(len(down_gantry_df_dict_all[repeat_id])):
                                    uuid_two = str(uuid.uuid4())
                                    down_gantry_df_dict_all[repeat_id + uuid_two] = [down_gantry_df_dict_all[repeat_id][i]]
                    # print("删除重复车辆", repeat_id)
                    del up_gantry_df_dict_all[repeat_id]
                    del down_gantry_df_dict_all[repeat_id]
                else:
                    # print("下游多趟次车辆未在上游出现", repeat_id)
                    pass
            else:
                # print("下游多趟次车辆与上游多趟次车辆一一匹配", repeat_id)
                pass

        if up_flag:
            time_dict = {}
            for lience, info in up_gantry_df_dict_all.items():
                if lience in down_gantry_df_dict_all.keys():
                    # print("匹配成功", lience, down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp'])
                    ctype = info[0]['车型']
                    if ctype not in time_dict.keys():
                        time_dict[ctype] = {}
                        time_dict[ctype]['time'] = []
                    time_ = down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp']
                    if 0 < time_ < 3600:
                        time_dict[ctype]['time'].append(time_)
                    else:
                        del time_dict[ctype]
            for ctype, time_list in time_dict.items():
                time_dict[ctype]['mean'] = np.mean(time_dict[ctype]['time'])
                # print(ctype, time_dict[ctype]['mean'])
                if time_dict[ctype]['mean'] <= 0:
                    print("平均时间小于0", ctype, time_dict[ctype]['mean'])
            # print("平均时间", time_dict)

            result = []
            for lience, info in up_gantry_df_dict_all.items():
                if lience in down_gantry_df_dict_all.keys():
                    # print("匹配成功", lience, down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp'])
                    to_write = info[0]
                    fen = int((down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp']) / 60)
                    miao = int((down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp']) % 60)
                    temp = str(fen) + "m" + str(miao) + "s"
                    to_write['time_diff'] = temp
                    to_write['transtime_down'] = down_gantry_df_dict_all[lience][0]['通行时间']
                    to_write['transtime_up'] = to_write['通行时间']
                    ctype = info[0]['车型']
                    if ctype not in time_dict.keys():
                        if down_gantry_df_dict_all[lience][0]['timestamp'] < info[0]['timestamp']:
                            to_write['match_type'] = -2
                        else:
                            to_write['match_type'] = 3
                    else:
                        time_mean = time_dict[ctype]['mean']

                        if 0 < down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp'] < time_mean:
                            to_write['match_type'] = 0
                        if time_mean <= down_gantry_df_dict_all[lience][0]['timestamp'] - info[0][
                            'timestamp'] < time_mean * 1.5:
                            to_write['match_type'] = 1
                        if time_mean * 1.5 <= down_gantry_df_dict_all[lience][0]['timestamp'] - info[0][
                            'timestamp'] < time_mean * 3:
                            to_write['match_type'] = 2
                        if time_mean * 3 <= down_gantry_df_dict_all[lience][0]['timestamp'] - info[0]['timestamp']:
                            to_write['match_type'] = 3
                        if down_gantry_df_dict_all[lience][0]['timestamp'] <= info[0]['timestamp']:
                            to_write['match_type'] = -2
                    if "警" in lience:
                        if lience[2] == '9':
                            to_write['police_car'] = 1
                        else:
                            to_write['police_car'] = 2
                    else:
                        to_write['police_car'] = 0

                    to_write['vlp'] = info[0]['车牌']
                    to_write['feevehicletype'] = info[0]['车型']

                    result.append(to_write)

                else:
                    # print("匹配失败", lience)
                    to_write = info[0]
                    to_write['vlp'] = info[0]['车牌']
                    to_write['feevehicletype'] = info[0]['车型']
                    to_write['time_diff'] = ""
                    to_write['transtime_down'] = ""
                    to_write['transtime_up'] = to_write['通行时间']
                    to_write['match_type'] = -1
                    if "警" in lience:
                        if lience[2] == '9':
                            to_write['police_car'] = 1
                        else:
                            to_write['police_car'] = 2
                    else:
                        to_write['police_car'] = 0
                    result.append(to_write)
            # print("result:", result)
            columns = ['vlp', 'feevehicletype', 'transtime_up', 'transtime_down', 'time_diff', 'match_type', 'police_car']
            df = pd.DataFrame(result, columns=columns)

            # 保存 DataFrame 到 CSV 文件
            output_file_path = up_path  # 替换为实际文件路径
            df.to_csv(output_file_path, index=False, encoding='utf-8')
        if down_flag:
            time_dict = {}
            for lience, info in down_gantry_df_dict_all.items():
                if lience in up_gantry_df_dict_all.keys():
                    ctype = info[0]['车型']
                    if ctype not in time_dict.keys():
                        time_dict[ctype] = {}
                        time_dict[ctype]['time'] = []
                    time_ = info[0]['timestamp'] - up_gantry_df_dict_all[lience][0]['timestamp']
                    if 0 < time_ < 3600:
                        time_dict[ctype]['time'].append(time_)
                    else:
                        del time_dict[ctype]
            for ctype, time_list in time_dict.items():
                time_dict[ctype]['mean'] = np.mean(time_dict[ctype]['time'])
            # print("平均时间", time_mean)
            result = []

            for lience, info in down_gantry_df_dict_all.items():
                if lience in up_gantry_df_dict_all.keys():
                    to_write = info[0]
                    ctype = info[0]['车型']

                    fen = int((info[0]['timestamp'] - up_gantry_df_dict_all[lience][0]['timestamp']) / 60)
                    miao = int((info[0]['timestamp'] - up_gantry_df_dict_all[lience][0]['timestamp']) % 60)
                    temp = str(fen) + "m" + str(miao) + "s"
                    if ctype not in time_dict.keys():
                        if info[0]['timestamp'] < up_gantry_df_dict_all[lience][0]['timestamp']:
                            to_write['match_type'] = -2
                        else:
                            to_write['match_type'] = 3
                    else:
                        time_mean = time_dict[ctype]['mean']
                        if 0 < info[0]['timestamp'] - up_gantry_df_dict_all[lience][0]['timestamp'] < time_mean:
                            to_write['match_type'] = 0
                        if time_mean <= info[0]['timestamp'] - up_gantry_df_dict_all[lience][0][
                            'timestamp'] < time_mean * 1.5:
                            to_write['match_type'] = 1
                        if time_mean * 1.5 <= info[0]['timestamp'] - up_gantry_df_dict_all[lience][0][
                            'timestamp'] < time_mean * 3:
                            to_write['match_type'] = 2
                        if time_mean * 3 <= info[0]['timestamp'] - up_gantry_df_dict_all[lience][0]['timestamp']:
                            to_write['match_type'] = 3
                        if info[0]['timestamp'] <= up_gantry_df_dict_all[lience][0]['timestamp']:
                            to_write['match_type'] = -2
                    if "警" in lience:
                        if lience[2] == '9':
                            to_write['police_car'] = 1
                        else:
                            to_write['police_car'] = 2
                    else:
                        to_write['police_car'] = 0
                    to_write['time_diff'] = temp
                    to_write['transtime_up'] = up_gantry_df_dict_all[lience][0]['通行时间']
                    to_write['transtime_down'] = to_write['通行时间']
                    to_write['vlp'] = info[0]['车牌']
                    to_write['feevehicletype'] = info[0]['车型']
                    result.append(to_write)
                else:
                    # print("匹配失败", lience)
                    to_write = info[0]
                    to_write['vlp'] = info[0]['车牌']
                    to_write['feevehicletype'] = info[0]['车型']
                    to_write['time_diff'] = ""
                    to_write['transtime_up'] = ""
                    to_write['transtime_down'] = to_write['通行时间']
                    to_write['match_type'] = -1
                    if "警" in lience:
                        if lience[2] == '9':
                            to_write['police_car'] = 1
                        else:
                            to_write['police_car'] = 2
                    else:
                        to_write['police_car'] = 0
                    result.append(to_write)

            columns = ['vlp', 'feevehicletype', 'transtime_up', 'transtime_down', 'time_diff', 'match_type',
                       'police_car']
            df = pd.DataFrame(result, columns=columns)
            # 保存 DataFrame 到 CSV 文件
            output_file_path = down_path  # 替换为实际文件路径
            df.to_csv(output_file_path, index=False, encoding='utf-8')

    def megred(self, up_path, down_path, all_path, flag=1):
        # 将上下游匹配数据合并为一个总文件
        up_data = self.get_match_data(up_path).copy()
        down_data = self.get_match_data(down_path).copy()
        # 提取时间戳列
        timestamps = up_data[:, 2]
        # 将时间戳列转换为 pandas.Timestamp 对象
        timestamps = pd.to_datetime(timestamps, format='%Y-%m-%d %H:%M:%S')
        # 使用 argsort 方法获取排序后的索引
        sort_indices = np.argsort(timestamps)
        # 根据排序后的索引对整个数组进行排序
        sorted_data = up_data[sort_indices]
        # # 根据下游时间戳排序插入部分下游车辆到csv中
        # down_time_list = []
        # for row in sorted_data:
        #     if type(row[3]) == str:
        #         down_time = pd.to_datetime(row[3], format='%Y-%m-%d %H:%M:%S')
        #         down_time_list.append(down_time)
        #     else:
        #         down_time_list.append(down_time_list[-1])
        # 根据上游时间戳排序插入部分下游车辆到csv中
        up_time_list = []
        for row in sorted_data:
            up_time_list.append(pd.to_datetime(row[2], format='%Y-%m-%d %H:%M:%S'))
        time_list = [up_time_list, 0]
        i = 0
        print("timmm1:", time.time())
        # 遍历原始数组
        for row in down_data:
            if type(row[2]) == str:
                continue
            new_row_time = pd.to_datetime(row[3], format='%Y-%m-%d %H:%M:%S')
            # 使用 numpy.searchsorted 查找插入位置
            insert_index = np.searchsorted(time_list[flag], new_row_time)
            insert_position = insert_index + i
            i += 1
            sorted_data = np.insert(sorted_data, insert_position, row, axis=0)

        df = pd.DataFrame(sorted_data)
        # 定义新的列名映射
        new_column_names = {
            0: 'vlp',
            1: 'feevehicletype',
            2: 'transtime_up',
            3: 'transtime_down',
            4: 'time_diff',
            5: 'match_type',
            6: 'police_car'
        }

        # 修改列名
        df = df.rename(columns=new_column_names)
        # # 打印更新后的列名
        # print("Updated columns in DataFrame:")
        # print(df.columns)
        # 保存 DataFrame 到 CSV 文件
        output_file_path = all_path  # 替换为实际文件路径
        df[['vlp', 'feevehicletype', 'transtime_up', 'transtime_down', 'time_diff', 'match_type', 'police_car']].to_csv(output_file_path, index=False, encoding='utf-8')

    def megred2(self, up_path, down_path, all_path, flag=1):
        # 将上下游匹配数据合并为一个总文件
        up_data = self.get_match_data(up_path).copy()
        down_data = self.get_match_data(down_path).copy()
        # 提取时间戳列
        timestamps = up_data[:, 2]
        # 将时间戳列转换为 pandas.Timestamp 对象
        timestamps = pd.to_datetime(timestamps, format='%Y-%m-%d %H:%M:%S')
        # 使用 argsort 方法获取排序后的索引
        sort_indices = np.argsort(timestamps)
        # 根据排序后的索引对整个数组进行排序
        sorted_data = up_data[sort_indices]
        result = []
        result_down = []
        for down_row in down_data:
            if type(down_row[2]) != str:
                result_down.append(down_row)
        result_down = np.array(result_down)
        down_timestamps = result_down[:, 3]
        down_timestamps = pd.to_datetime(down_timestamps, format='%Y-%m-%d %H:%M:%S')
        sort_down_indices = np.argsort(down_timestamps)
        sorted_down_data = result_down[sort_down_indices]

        down_i = 0
        # 遍历上游数据
        for up_row in sorted_data:
            up_time = pd.to_datetime(up_row[2], format='%Y-%m-%d %H:%M:%S')
            # 遍历剩余的下游数据
            while down_i < len(sorted_down_data):
                down_row = sorted_down_data[down_i]
                down_time = pd.to_datetime(down_row[3], format='%Y-%m-%d %H:%M:%S')
                if up_time <= down_time:
                    result.append(up_row)
                    break
                else:
                    result.append(down_row)
                    down_i += 1
            else:
                # 如果没有找到合适的 down_time，直接插入 up_row
                result.append(up_row)
        # 添加任何剩余的下游数据
        while down_i < len(sorted_down_data):
            result.append(sorted_down_data[down_i])
            down_i += 1

        df = pd.DataFrame(result)
        # 定义新的列名映射
        new_column_names = {
            0: 'vlp',
            1: 'feevehicletype',
            2: 'transtime_up',
            3: 'transtime_down',
            4: 'time_diff',
            5: 'match_type',
            6: 'police_car'
        }

        # 修改列名
        df = df.rename(columns=new_column_names)
        # # 打印更新后的列名
        # print("Updated columns in DataFrame:")
        # print(df.columns)
        # 保存 DataFrame 到 CSV 文件
        output_file_path = all_path  # 替换为实际文件路径
        df[['vlp', 'feevehicletype', 'transtime_up', 'transtime_down', 'time_diff', 'match_type', 'police_car']].to_csv(
            output_file_path, index=False, encoding='utf-8')

    def get_match_data(self, path):
        # 使用 chardet 检测文件编码
        with open(path, 'rb') as f:
            result = chardet.detect(f.read(10000))
        detected_encoding = result['encoding']
        # print(f"Detected encoding: {detected_encoding}")

        # 使用检测到的编码读取 CSV 文件
        df = pd.read_csv(path, encoding=detected_encoding)
        # print(df.head())

        # a = df.to_dict(orient='records')
        df_np = df.to_numpy()
        return df_np

    def get_mean_time(self, df_np):
        total_num = len(df_np)
        # 初始化一个空列表来存储总秒数
        total_seconds = []
        for row in df_np:
            time_diff = row[4]
            # if type(time_diff) != str:
            #     continue
            if int(row[5]) < 0:
                continue
            # 解析时间差字符串
            parts = time_diff.split('m')
            fen = int(parts[0])  # 分钟数
            miao = int(parts[1].split('s')[0])  # 秒数
            # 计算总秒数
            seconds = fen * 60 + miao
            total_seconds.append(seconds)
            if seconds < 0:
                print("time_diff: ", time_diff, row)
        # 将列表转换为 NumPy 数组
        total_seconds_array = np.array(total_seconds)
        # 计算总和
        total_seconds_sum = np.sum(total_seconds_array)
        # 计算平均值
        seconds_average = np.mean(total_seconds_array)
        # 计算最大值
        seconds_max = np.max(total_seconds_array)
        # 计算最小值
        seconds_min = np.min(total_seconds_array)

        print(f"Total seconds: {total_seconds_sum}, seconds_average: {seconds_average}, num: {len(total_seconds)}, "
              f"total_num: {total_num}, max: {seconds_max}, min: {seconds_min}")
        return total_seconds_sum, seconds_average, seconds_max, seconds_min

    def get_vehicle_data(self, df_np, vehicle_name):
        # 定义条件：第一列等于 "A123"
        condition = df_np[:, 0] == vehicle_name
        # 使用布尔索引获取符合条件的行
        matching_rows = df_np[condition]

        return matching_rows

    def transform_transaction_id(self, s):
        # 分割原始流水号
        parts = s.split('-')
        # 假设流水号的格式是：
        # G000551003000310010-G000551003000410010-2024-08-04
        # 我们需要交换前两部分
        if len(parts) >= 3:
            # 交换前两部分
            parts[0], parts[1] = parts[1], parts[0]
            # 重新组合成新的流水号
            new_s = '-'.join(parts)
            return new_s
        else:
            return "Invalid format"

    def run(self):
        self.get_gantry_ID()
        self.get_data()
        # # "10T"表示10分钟，“1H”表示1小时
        # total_flow, vehicle_percentage = self.get_flow(self.up_gantry_df, time_interval='1H')
        # print(total_flow)

        # 生成上下游匹配csv文件
        file_name = os.path.basename(self.file_path)
        # parts = file_name.split('-')
        # if parts[0][-5] == '2':
        #     file_name = self.transform_transaction_id(file_name)

        output_path = r'D:\GJ\项目\事故检测\output\绵广高速'
        # .replace(',', '-')
        output = os.path.join(output_path, os.path.basename(self.file_path).split('.')[0])
        if not os.path.exists(output):
            os.makedirs(output)
        up_path = os.path.join(output, 'up_' + os.path.splitext(file_name)[0] + '.csv')
        down_path = os.path.join(output, 'down_' + os.path.splitext(file_name)[0] + '.csv')
        all_path = os.path.join(output, 'all_1111' + os.path.splitext(file_name)[0] + '.csv')
        print("output path: ", output)
        print(up_path, down_path, all_path)

        # print("time1: ", time.time())
        # 上下游各自匹配文件
        self.matching_json(self.up_gantry_df, self.down_gantry_df, up_path, down_path)
        # print("time2: ", time.time())
        # 合并文件 flag为0（根据上游时间戳排序）或1（根据下游时间戳排序）
        self.megred2(up_path, down_path, all_path, flag=0)
        # print("time3: ", time.time())


if __name__ == '__main__':
    file_path = r'D:\GJ\项目\事故检测\绵广高速事故相关流水及牌识\流水\G000551002000310010-G000551003000110010-2024-02-04-流水.xlsx'

    gantry = Gantry(file_path)
    gantry.run()

    # # top_dir = r'D:\GJ\项目\事故检测\标定及检验事件数据\用于标定'
    # # top_dir = r'D:\GJ\项目\事故检测\标定及检验事件数据\用于验证仿真检测结果'
    # top_dir = r'D:\GJ\项目\事故检测\纳黔高速事故相关流水及牌识\流水'
    # # 获取目录下的所有文件和文件夹名
    # files_and_dirs = os.listdir(top_dir)
    # ii = 0
    # # 遍历文件和文件夹
    # for entry in files_and_dirs:
    #     full_path = os.path.join(top_dir, entry)
    #     gantry = Gantry(full_path)
    #     gantry.run()
    #     ii += 1
    #     print(ii)
    #     time.sleep(0.01)
